﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Telerik.Web.Mvc;
using System.Diagnostics;
using JdSoft.Apple.Apns.Feedback;
using JdSoft.Apple.Apns.Notifications;

namespace Presentation.Web.Admin.Controllers
{
    [HandleError]
    public class PushController : Infrastructure.Crosscutting.NetFramework.Controllers.BaseController
    {
        #region added by yjihrp 2013.3.8.15.03

        string sessionKeyRepush = "session_key_repush";

        string sessionKeyPushContent = "session_key_push_content";

        #endregion

        Application.Admin.MobileClient.IMobileClientService clientService;

        Application.Admin.MobileClient.IMobileClientStartLogService startLogService;

        Application.Admin.Push.IPushContentsService contentService;

        Application.Admin.Push.IPushLogService pushLogService;

        Application.Admin.Push.IAutoPushDetailService detailService;

        Application.Admin.Push.IAutoPushService autoPushService;

        Application.Admin.Push.IAutoPushTimerService timerService;

        Presentation.Web.Admin.PushNoteService noteService;

        public PushController(Infrastructure.Crosscutting.NetFramework.IWorkContext work,
            Application.Admin.MobileClient.IMobileClientService client,
            Application.Admin.MobileClient.IMobileClientStartLogService startLog,
            Application.Admin.Push.IPushContentsService content,
            Application.Admin.Push.IPushLogService log,
            Application.Admin.Push.IAutoPushDetailService detail,
            Application.Admin.Push.IAutoPushService autoPush,
            Application.Admin.Push.IAutoPushTimerService timer,
            Presentation.Web.Admin.PushNoteService note)
            : base(work)
        {
            if (client == null)
            {
                throw new ArgumentNullException("clientService is null");
            }
            if (startLog == null)
            {
                throw new ArgumentNullException("startLogService is null");
            }
            if (content == null)
            {
                throw new ArgumentNullException("contentService is null");
            }
            if (log == null)
            {
                throw new ArgumentNullException("logService is null");
            }

            if (detail == null)
            {
                throw new ArgumentNullException("detailService is null");
            }
            if (autoPush == null)
            {
                throw new ArgumentNullException("autoPushService is null");
            }
            if (timer == null)
            {
                throw new ArgumentNullException("timerService is null");
            }
            if (note == null)
            {
                throw new ArgumentNullException("noteService is null");
            }
            clientService = client;
            startLogService = startLog;
            contentService = content;
            pushLogService = log;
            detailService = detail;
            autoPushService = autoPush;
            timerService = timer;
            noteService = note;
        }

        #region hand push

        [HttpGet]
        public ViewResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Index(string contents, int sleepBetweenNote, int connNum, int sendRetry, int reconnectDelay, int badge)
        {
            var res = false;
            var message = "";
            //
            var failClientList = Session[sessionKeyRepush] as Dictionary<Domain.Entity.MobileClient, bool>;
            var total = 0;
            if (failClientList != null)
            {
                failClientList.Clear();
            }
            else
            {
                failClientList = new Dictionary<Domain.Entity.MobileClient, bool>();
            }

            if (!string.IsNullOrEmpty(contents) & contents.Length <= 256)
            {
                var deviceList = this.GetMobileClientTrueState();
                //测试用的
                //var idList = new List<int>() { 121, 2142 };
                //var deviceList = clientService.GetList().Where(d => idList.Contains(d.Id));
                //发送
                if (deviceList != null && deviceList.Any())
                {
                    #region check

                    if (sendRetry < 0 || sendRetry > 10)
                    {
                        message = "请填写正确的重试次数";
                        return Json(new { success = res, message = message, total = total, left = -1 }, JsonRequestBehavior.AllowGet);
                    }
                    if (connNum < 0 || connNum > 50)
                    {
                        message = "请填写正确的推送连接数";
                        return Json(new { success = res, message = message, total = total, left = -1 }, JsonRequestBehavior.AllowGet);
                    }
                    if (sleepBetweenNote <= 0)
                    {
                        message = "请填写正确的客户端推送时间间隔,提示该时间必须大于0";
                        return Json(new { success = res, message = message, total = total, left = -1 }, JsonRequestBehavior.AllowGet);
                    }
                    if (reconnectDelay < 0)
                    {
                        message = "请填写正确的推送成功后重新连接延迟时间";
                        return Json(new { success = res, message = message, total = total, left = -1 }, JsonRequestBehavior.AllowGet);
                    }

                    #endregion

                    var contentModel = new Domain.Entity.PushContents();
                    contentModel.AddTime = System.DateTime.Now;
                    contentModel.Content = contents;
                    contentModel.ExpiredDateTime = System.DateTime.Now;
                    contentModel.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                    contentModel.SortNum = 0;
                    contentModel.State = true;
                    contentService.Add(contentModel, this.WorkContext.CurrentUser);
                    if (contentModel.Id > 0)
                    {
                        noteService.ConnNum = connNum;
                        noteService.ReconnectDelay = reconnectDelay;
                        noteService.SendRetry = sendRetry;
                        noteService.SleepBetweenNote = sleepBetweenNote;
                        noteService.PushHostIp = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                        noteService.DataUpdate = badge;
                        noteService.PushUser = this.WorkContext.CurrentUser;
                        //edited by yjihrp 2013.3.8.15.7
                        //原来推送方式
                        //res = noteService.PushBase(deviceList , contentEntity);

                        //现在推送方式 保存推送记录到session 
                        total = deviceList.Count;
                        var temp = noteService.PushListOneByOne(deviceList.ToList(), contentModel);
                        if (temp != null && temp.Count > 0)
                        {
                            foreach (var item in temp)
                            {
                                if (!item.Value)
                                {
                                    failClientList.Add(item.Key, item.Value);
                                }
                            }
                        }
                        //记录当前的推送的内容
                        Session[sessionKeyPushContent] = contentModel;
                        Session[sessionKeyRepush] = failClientList;
                        //end edited by yjihrp 2013.3.8.15.7
                    }
                    else
                    {
                        message = "将推送内容添加到数据库失败了。";
                    }
                }
                else
                {
                    message = "暂时没用有效的设备安装IMAP";
                }
            }
            else
            {
                message = "推送内容不能为空T_T";
            }
            //edited by yjihrp 2013.3.8.15.7
            //原来返回内容
            //return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
            //现在返回内容
            return Json(new
            {
                success = res,
                message = message,
                total = total,
                left = failClientList.Where(d => d.Value == false).Count()
            }, JsonRequestBehavior.AllowGet);
            //end edited by yjihrp 2013.3.8.15.7
        }

        /// <summary>
        /// added by yjihrp 2013.3.8.18.14
        /// 重新推送失败的客户端
        /// </summary>
        /// <param name="sleepBetweenNote"></param>
        /// <param name="connNum"></param>
        /// <param name="sendRetry"></param>
        /// <param name="reconnectDelay"></param>
        /// <param name="badge"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ReIndex(int sleepBetweenNote, int connNum, int sendRetry, int reconnectDelay, int badge)
        {
            //之前推送的记录
            var preFailClientList = Session[sessionKeyRepush] as Dictionary<Domain.Entity.MobileClient, bool>;
            //保存重新推送记录
            var failClientList = new Dictionary<Domain.Entity.MobileClient, bool>();
            var total = 0;
            var content = Session[sessionKeyPushContent] as Domain.Entity.PushContents;
            if (preFailClientList != null && preFailClientList.Count > 0 && content != null)
            {
                var currentPushList = preFailClientList.Where(d => d.Value == false).ToList();
                noteService.ConnNum = connNum;
                noteService.ReconnectDelay = reconnectDelay;
                noteService.SendRetry = sendRetry;
                noteService.SleepBetweenNote = sleepBetweenNote;
                noteService.PushHostIp = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                noteService.DataUpdate = badge;
                foreach (var item in currentPushList)
                {
                    //一个一个推送
                    var res = noteService.PushSingle(item.Key, content);
                    if (!res)
                    {
                        failClientList.Add(item.Key, res);
                    }
                    total++;
                    System.Threading.Thread.Sleep(sleepBetweenNote * 1000);
                }
                //记录当前的推送的内容
                Session[sessionKeyPushContent] = content;
                Session[sessionKeyRepush] = failClientList;
            }
            return Json(new
            {
                success = true,
                message = "",
                total = total,
                left = failClientList.Where(d => d.Value == false).Count()
            }, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region auto push

        public ViewResult AutoPushIndex()
        {
            var data = this.GetAutoPushTrueState().OrderByDescending(e => e.Id);
            return View(data.ToList());
        }

        [GridAction]
        public JsonResult AjaxAutoPushIndex(string searchKey)
        {
            var data = this.GetAutoPushTrueState();
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.Name.Contains(searchKey));
            }
            var dto = data.OrderByDescending(e => e.Id).ToList();
            var model = new GridModel<Application.Admin.Dto.AutoPushDto>
            {
                Data = dto,
                Total = dto.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpPost]
        public JsonResult AddAutoPush(Application.Admin.Dto.AutoPushDto dto)
        {
            var res = false;
            var message = "";

            #region checked

            if (string.IsNullOrEmpty(dto.Name))
            {
                message = "定时推送名不能为空";
                return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
            }
            if (string.IsNullOrEmpty(dto.Content))
            {
                message = "定时推送内容不能为空";
                return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
            }
            if (dto.ExpiredDateTime < System.DateTime.Now)
            {
                message = "过期时间不能小于当前时间";
                return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
            }
            #endregion

            var content = new Domain.Entity.PushContents();
            content.AddTime = System.DateTime.Now;
            content.Content = string.IsNullOrEmpty(dto.Content) ? "" : dto.Content.Trim();
            content.ExpiredDateTime = System.DateTime.Now;
            content.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
            content.SortNum = 0;
            content.State = true;
            contentService.Add(content, this.WorkContext.CurrentUser);
            if (content.Id > 0)
            {
                dto.AddTime = System.DateTime.Now;
                dto.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                dto.SortNum = 0;
                dto.ContentId = content.Id;
                var entity = dto.ToEntity();
                autoPushService.Add(entity, this.WorkContext.CurrentUser);
                if (entity.Id <= 0)
                {
                    message = "添加定时推送记录失败T_T！";
                }
                else
                {
                    res = true;
                }
            }
            else
            {
                message = "添加推送内容失败了T_T";
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult DeleteAutoPush(int id)
        {
            var delete = autoPushService.Get(id);
            if (delete != null)
            {
                autoPushService.DeleteTrue(delete, this.WorkContext.CurrentUser);
            }
            var data = this.GetAutoPushTrueState().OrderByDescending(e => e.Id).ToList();
            var model = new GridModel<Application.Admin.Dto.AutoPushDto>
            {
                Data = data,
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpPost]
        public JsonResult MulDeleteAutoPush(FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = autoPushService.DeleteTrue(selectedList.ToIntList(), this.WorkContext.CurrentUser);
                message = res == true ? "" : "删除失败了，T_T";
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult EditAutoPush(Application.Admin.Dto.AutoPushDto dto)
        {
            if (dto.Id > 0)
            {
                var auto = autoPushService.Get(dto.Id);
                if (auto != null)
                {
                    auto.Name = string.IsNullOrEmpty(dto.Name) ? "" : dto.Name.Trim();
                    auto.Remark = string.IsNullOrEmpty(dto.Remark) ? "" : dto.Remark.Trim();
                    auto.IntervalTime = dto.IntervalTime;
                    auto.ExpiredDateTime = dto.ExpiredDateTime;
                    autoPushService.Modify(auto, this.WorkContext.CurrentUser);
                    var content = contentService.Get(dto.ContentId);
                    if (content != null && content.Id > 0)
                    {
                        content.Content = string.IsNullOrEmpty(dto.Content) ? "" : dto.Content.Trim();
                        contentService.Modify(content, this.WorkContext.CurrentUser);
                    }
                }
            }
            var data = this.GetAutoPushTrueState().OrderByDescending(e => e.Id).ToList();
            var model = new GridModel<Application.Admin.Dto.AutoPushDto>
            {
                Data = data,
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpGet]
        public JsonResult SearchAutoPush(string term)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var data = this.GetAutoPushTrueState()
                    .Where(e => e.Name.Contains(term.Trim()))
                    .OrderBy(e => e.Id).Take(10)
                    .Select(e => e.Name).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                var data = this.GetAutoPushTrueState()
                        .OrderBy(e => e.Id).Take(10)
                        .Select(e => e.Name).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region auto push timer

        public ViewResult AutoPushTimerIndex()
        {
            var data = this.GetAutoPushTimerTrueState();
            return View(data.ToDto());
        }

        [GridAction]
        public JsonResult AjaxAutoPushTimerIndex()
        {
            var data = this.GetAutoPushTimerTrueState();
            var model = new GridModel<Domain.Dto.AutoPushTimerDto>
            {
                Data = data.ToDto(),
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [GridAction]
        [HttpPost]
        public JsonResult AddAutoPushTimer(Domain.Dto.AutoPushTimerDto dto)
        {
            dto.AddTime = System.DateTime.Now;
            dto.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
            dto.SortNum = 0;
            dto.State = true;
            var entity = dto.ToEntity();
            timerService.Add(entity, this.WorkContext.CurrentUser);
            var data = this.GetAutoPushTimerTrueState();
            var model = new GridModel<Domain.Dto.AutoPushTimerDto>
            {
                Data = data.ToDto(),
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [GridAction]
        [HttpPost]
        public JsonResult DeleteAutoPushTimer(int id)
        {
            var delete = timerService.Get(id);
            if (delete != null)
            {
                timerService.DeleteTrue(delete, this.WorkContext.CurrentUser);
            }
            var data = this.GetAutoPushTimerTrueState();
            var model = new GridModel<Domain.Dto.AutoPushTimerDto>
            {
                Data = data.ToDto(),
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpPost]
        public JsonResult MulDeleteAutoPushTimer(FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = timerService.DeleteTrue(selectedList.ToIntList(), this.WorkContext.CurrentUser);
                message = res == true ? "" : "删除失败了，T_T";
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult EditAutoPushTimer(Domain.Dto.AutoPushTimerDto dto)
        {
            var entity = timerService.Get(dto.Id);
            if (entity != null)
            {
                entity.BeginHour = dto.BeginHour;
                entity.BeninMinute = dto.BeninMinute;
                entity.EndHour = dto.EndHour;
                entity.EndMinute = dto.EndMinute;
                timerService.Modify(entity, this.WorkContext.CurrentUser);
            }
            var data = this.GetAutoPushTimerTrueState();
            var model = new GridModel<Domain.Dto.AutoPushTimerDto>
            {
                Data = data.ToDto(),
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        #endregion

        #region auto push detail

        [HttpPost]
        public PartialViewResult AutoPushDetail(int id)
        {
            var data = this.GetAutoPushDetailTrueState(id).ToDto();
            ViewBag.id = id;
            return PartialView("_AutoPushDetail", data);
        }

        [HttpPost]
        public JsonResult EditAutoPushDetail(FormCollection edit)
        {
            var res = false;
            var message = "";
            var pushIdStr = edit.Get("autoPushId");
            var pushId = 0;
            int.TryParse(pushIdStr, out pushId);
            if (pushId > 0)
            {
                try
                {
                    //已经有的时间段
                    var has = detailService.GetList().Where(e => e.AutoPushId == pushId).ToList();
                    var timerStr = edit.GetValues("timer");
                    if (timerStr != null && timerStr.Count() > 0)
                    {
                        //用户选中的
                        //添加用户选中的
                        var timerList = timerStr.ToIntList();
                        foreach (var it in timerList)
                        {
                            if (!has.Where(e => e.TimerId == it).Any())
                            {
                                var temp = new Domain.Entity.AutoPushDetail();
                                temp.AddTime = System.DateTime.Now;
                                temp.AutoPushId = pushId;
                                temp.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                                temp.SortNum = 0;
                                temp.State = true;
                                temp.TimerId = it;
                                detailService.Add(temp, this.WorkContext.CurrentUser);
                            }
                        }
                        //删除已经有的
                        foreach (var item in has)
                        {
                            if (!timerList.Contains(item.TimerId))
                            {
                                detailService.DeleteTrue(item, this.WorkContext.CurrentUser);
                            }
                        }
                        res = true;
                    }
                    else
                    {
                        //删除所有
                        foreach (var item in has)
                        {
                            detailService.DeleteTrue(item, this.WorkContext.CurrentUser);
                        }
                        res = true;
                    }
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                }
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region push log

        public ViewResult PushLogIndex()
        {
            var data = pushLogService.GetPushLogDtoTrueState().OrderByDescending(e => e.Id);
            return View(data.ToList());
        }

        [GridAction]
        public JsonResult AjaxPushLogIndex(string searchKey, int resultType)
        {
            resultType = resultType < 0 ? 0 : resultType;
            var data = pushLogService.GetPushLogDtoTrueState(resultType);
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.Content.Contains(searchKey));
            }
            var dto = data.OrderByDescending(e => e.Id).ToList();
            var model = new GridModel<Application.Admin.Dto.PushLogDto>
            {
                Data = dto,
                Total = dto.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpPost]
        public JsonResult DeletePushLog(int id)
        {
            var res = false;
            var message = "";
            var delete = pushLogService.Get(id);
            if (delete != null)
            {
                try
                {
                    if (pushLogService.DeleteTrue(delete, this.WorkContext.CurrentUser))
                    {
                        res = true;
                    }
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                }
            }
            else
            {
                message = "没有找到你要修改的对象";
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult MulDeletePushLog(FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = pushLogService.DeleteTrue(selectedList.ToIntList(), this.WorkContext.CurrentUser);
                message = res == true ? "" : "删除失败了，T_T";
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult ClearAllPushLog()
        {
            var res = false;
            var message = "";
            try
            {
                var all = pushLogService.GetList().Select(e => e.Id);
                pushLogService.DeleteTrue(all.ToList(), this.WorkContext.CurrentUser);
                res = true;
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }


        [HttpGet]
        public JsonResult SearchPushLog(string term, int resultType)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var data = pushLogService.GetPushLogDtoTrueState()
                    .Where(e => e.Result == resultType)
                    .Where(e => e.Content.Contains(term.Trim()))
                    .OrderBy(e => e.Id).Take(10)
                    .Select(e => e.Content).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                var data = pushLogService.GetPushLogDtoTrueState()
                        .Where(e => e.Result == resultType)
                        .OrderBy(e => e.Id).Take(10)
                        .Select(e => e.Content).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region push content

        public ViewResult PushContentIndex()
        {
            var data = this.GetPushContentsTrueState();
            return View(data.ToDto());
        }

        [GridAction]
        public JsonResult AjaxPushContentIndex(string searchKey)
        {
            var data = this.GetPushContentsTrueState();
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.Content.Contains(searchKey));
            }
            var dto = data.ToDto();
            var model = new GridModel<Domain.Dto.PushContentsDto>
            {
                Data = dto,
                Total = dto.Count()
            };
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult DeletePushContent(int id)
        {
            var delete = contentService.Get(id);
            if (delete != null)
            {
                contentService.DeleteTrue(delete, this.WorkContext.CurrentUser);
            }
            var data = this.GetPushContentsTrueState().ToDto();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult MulDeletePushContent(FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = contentService.DeleteTrue(selectedList.ToIntList(), this.WorkContext.CurrentUser);
                message = res == true ? "" : "删除失败了，T_T";
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult SearchPushContent(string term)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var data = this.GetPushContentsTrueState().Where(e => e.Content.Contains(term.Trim()))
                            .OrderBy(e => e.Id).Take(10)
                            .Select(e => e.Content).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                var data = this.GetPushContentsTrueState().OrderBy(e => e.Id).Take(10)
                            .Select(e => e.Content).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region feed back event

        protected void FeedbackIndex(object sender, Feedback feedback)
        {
            if (feedback != null && !string.IsNullOrEmpty(feedback.DeviceToken))
            {
                var client = clientService.GetList().Where(e => e.DeviceToken == feedback.DeviceToken).FirstOrDefault();
                if (client != null)
                {
                    client.State = false;
                    clientService.Modify(client, this.WorkContext.CurrentUser);
                }
            }
            Debug.WriteLine(string.Format("Feedback - Timestamp: {0} - DeviceId: {1}", feedback.Timestamp, feedback.DeviceToken));
        }

        protected void FeedbackError(object sender, Exception ex)
        {
            var error = Infrastructure.Crosscutting.Comm.Service.LogCreateService.CreateLog();
            error.FullMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
            error.ShortMessage = "feed back error";
            Infrastructure.Data.Uow.Log.LoggerRepositoryManager.AddLogInfo(error);
            Debug.WriteLine(string.Format("Error: {0}", ex.Message));
        }

        #endregion

        #region util

        protected IQueryable<Domain.Entity.AutoPushDetail> GetAutoPushDetailTrueState(int id)
        {
            var data = detailService.GetList().Where(e => e.AutoPushId == id);
            return data;
        }

        protected IQueryable<Domain.Entity.AutoPushTimer> GetAutoPushTimerTrueState()
        {
            var data = this.timerService.GetList().Where(e => e.State == true)
                .OrderByDescending(e => e.Id);
            return data;
        }

        protected IQueryable<Application.Admin.Dto.AutoPushDto> GetAutoPushTrueState()
        {
            var data = (from auto in autoPushService.GetList()
                        join content in contentService.GetList() on auto.ContentId equals content.Id
                        orderby auto.Id descending
                        select new Application.Admin.Dto.AutoPushDto
                        {
                            AddTime = auto.AddTime,
                            Content = content.Content,
                            ContentId = auto.ContentId,
                            Id = auto.Id,
                            IntervalTime = auto.IntervalTime,
                            IpAddress = auto.IpAddress,
                            Name = auto.Name,
                            Remark = auto.Remark,
                            SortNum = auto.SortNum,
                            State = auto.State,
                            ExpiredDateTime = auto.ExpiredDateTime
                        });
            return data.OrderByDescending(e => e.Id);
        }

        protected IQueryable<Domain.Entity.PushContents> GetPushContentsTrueState()
        {
            var data = contentService.GetList().Where(e => e.State == true)
                .OrderByDescending(e => e.Id).ThenByDescending(e => e.AddTime);
            return data;
        }

        protected IQueryable<Domain.Entity.PushLog> GetPushLogTrueState()
        {
            var data = pushLogService.GetList().Where(e => e.State == true)
                .OrderByDescending(e => e.Id).ThenByDescending(e => e.AddTime);
            return data;
        }

        protected List<Domain.Entity.MobileClient> GetMobileClientTrueState()
        {
            var fbService = new JdSoft.Apple.Apns.Feedback.FeedbackService(PreAdminConfigSettingService.IsPushSandbox,
                Server.MapPath(PreAdminConfigSettingService.PushKeyFilePath), PreAdminConfigSettingService.PushKeyFilePwd);
            fbService.Error += new FeedbackService.OnError(FeedbackError);
            fbService.Feedback += new FeedbackService.OnFeedback(FeedbackIndex);
            //从apns上拿到装过imap，但双删除了的token
            fbService.Run();
            fbService.Dispose();
            //end 从apns上拿到装过imap，但双删除了的token

            var expired = System.DateTime.Now.AddMonths(-6);
            //从启动日志里面找到近6个月有效的client id
            var clientIdList = startLogService.GetList().Where(e => e.AddTime > expired)
                .Select(e => e.ClientId).Distinct().ToList();
            //从Id里面找到 token
            var deviceList = clientService.GetList()
                .Where(e => clientIdList.Contains(e.Id))
                .Where(e => e.DeviceToken.Length == 64)
                .Where(e => e.State == true)
                .Distinct().ToList();
            return deviceList;
        }

        #endregion

    }
}
